from django.contrib import admin
from django.utils.html import format_html
from django import forms
from .models import (
    DjChef, DjChefVerification, VerificationRecord
)

# 定义城市选项常量
CITY_CHOICES = [
    ('', '---------'),  # 空选项
    ('北京', '北京'),
    ('上海', '上海'),
    ('杭州', '杭州'),
    ('深圳', '深圳'),
    ('广州', '广州'),
]

# 厨师端认证内联
class DjChefVerificationInline(admin.StackedInline):
    model = DjChefVerification
    extra = 0
    fields = ('id_card_number', 'id_card_front', 'id_card_back', 'health_certificate', 
              'health_cert_expiry', 'chef_certificate', 'years_of_experience', 'specialty')


@admin.register(DjChef)
class DjChefAdmin(admin.ModelAdmin):
    list_display = ('id',
        'nickname', 'phone_number', 'verification_status', 'specialty','rating',
        'user_status', 'background_approved', 'city', 'service_area',
        'background_preview', 'action_buttons'
    )
    list_filter = ('verification_status', 'user_status', 'background_approved', 'city')
    search_fields = ('nickname', 'phone_number', 'real_name', 'city', 'service_area')
    inlines = [DjChefVerificationInline]
    actions = [
        'approve_background', 'reject_background',
        'set_verification_pending', 'set_verification_verified',  # 移除拒绝认证动作
        'set_active', 'set_suspended', 'set_banned'
    ]
    
    fieldsets = (
        ('基础信息', {'fields': ('user', 'openid', 'nickname', 'real_name', 'avatar', 'background', 'background_preview','specialty')}),
        ('位置信息', {'fields': ('city', 'service_area')}),
        ('状态管理', {'fields': ('verification_status', 'user_status', 'background_approved')}),
        ('联系方式', {'fields': ('phone_number', 'email')}),
        ('钱包信息', {'fields': ('balance',)}),
        ('评分信息', {'fields': ('rating', 'review_count')}),
        ('元数据', {'fields': ('created_at', 'updated_at', 'last_login')}),
    )
    
    readonly_fields = ('created_at', 'updated_at', 'openid', 'last_login', 'background_preview')

    # 背景图查看按钮
    def background_preview(self, obj):
        if obj.background:
            return format_html(
                '<a href="{}" target="_blank" class="button">查看背景图</a>',
                obj.background
            )
        return "-"
    background_preview.short_description = "背景图"

    # 修复city字段表单错误
    def formfield_for_dbfield(self, db_field, request, **kwargs):
        if db_field.name == 'city':
            return forms.ChoiceField(
                choices=CITY_CHOICES,
                required=False,
                initial=db_field.default if db_field.default else ''
            )
        return super().formfield_for_dbfield(db_field, request, **kwargs)

    # 操作按钮（移除拒绝认证选项）
    def action_buttons(self, obj):
        return format_html(
            '<div style="display: flex; gap: 5px;">'
            '<a class="button" href="{}?background_approved={}">{}</a>'
            '<a class="button" href="{}?verification_status=pending">待审核</a>'
            '<a class="button" href="{}?verification_status=verified">通过认证</a>'
            '</div>',
            f"{obj.id}/change/",
            not obj.background_approved,
            "通过背景" if not obj.background_approved else "拒绝背景",
            f"{obj.id}/change/",
            f"{obj.id}/change/"
        )
    action_buttons.short_description = "快速操作"

    @admin.action(description='审核通过背景图')
    def approve_background(self, request, queryset):
        queryset.update(background_approved=True)

    @admin.action(description='拒绝背景图')
    def reject_background(self, request, queryset):
        queryset.update(background_approved=False)

    @admin.action(description='设为认证中')
    def set_verification_pending(self, request, queryset):
        queryset.update(verification_status='pending')

    @admin.action(description='设为已认证')
    def set_verification_verified(self, request, queryset):
        queryset.update(verification_status='verified')

    @admin.action(description='设为活跃状态')
    def set_active(self, request, queryset):
        queryset.update(user_status='active')

    @admin.action(description='设为暂停服务')
    def set_suspended(self, request, queryset):
        queryset.update(user_status='suspended')

    @admin.action(description='设为禁用')
    def set_banned(self, request, queryset):
        queryset.update(user_status='banned')


class DjChefVerificationForm(forms.ModelForm):
    class Meta:
        model = DjChefVerification
        fields = '__all__'
        widgets = {
            'id_card_number': forms.TextInput(attrs={'required': False}),
            'id_card_front': forms.ClearableFileInput(attrs={'required': False}),
            'id_card_back': forms.ClearableFileInput(attrs={'required': False}),
            'passport_image': forms.ClearableFileInput(attrs={'required': False}),
            'health_certificate': forms.ClearableFileInput(attrs={'required': False}),
            'health_cert_expiry': forms.DateInput(attrs={'required': False, 'type': 'date'}),
            'chef_certificate': forms.ClearableFileInput(attrs={'required': False}),
            'years_of_experience': forms.NumberInput(attrs={'required': False}),
            'specialty': forms.TextInput(attrs={'required': False}),
            'reviewer_notes': forms.Textarea(attrs={'rows': 3, 'cols': 40}),  # 调整输入框大小
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # 优化点1：处理pending状态下的审核按钮初始状态
        instance = kwargs.get('instance')
        if instance and hasattr(instance.chef, 'verification_status'):
            # 当厨师认证状态为pending时，强制审核按钮为未勾选
            if instance.chef.verification_status == 'pending':
                self.fields['reviewer_approved'].initial = False
            # 对于已审核通过/未通过的状态，保持数据库记录的值
            else:
                self.fields['reviewer_approved'].initial = instance.reviewer_approved


@admin.register(DjChefVerification)
class DjChefVerificationAdmin(admin.ModelAdmin):
    form = DjChefVerificationForm
    
    list_display = (
        'id', 'chef', 'id_card_front_thumbnail', 'id_card_back_thumbnail',
        'passport_thumbnail', 'health_cert_thumbnail', 'chef_cert_thumbnail',
        'reviewer_approved', 'action_buttons'
    )
    list_filter = ('reviewer_approved', 'chef__verification_status')  # 增加状态筛选
    search_fields = ('chef__nickname', 'chef__real_name', 'id_card_number')
    
    fieldsets = (
        ('关联信息', {
            'fields': ('chef',),
            'description': '此字段为必填项'
        }),
        ('身份证信息（可选）', {
            'fields': (
                'id_card_number', 
                'id_card_front', 'id_card_front_preview',
                'id_card_back', 'id_card_back_preview'
            ),
            'classes': ('collapse',)
        }),
        ('其他证件（可选）', {
            'fields': (
                'passport_image', 'passport_preview',
                'health_certificate', 'health_cert_preview',
                'health_cert_expiry',
                'chef_certificate', 'chef_cert_preview'
            ),
            'classes': ('collapse',)
        }),
        ('职业信息（可选）', {
            'fields': ('years_of_experience', 'specialty'),
            'classes': ('collapse',)
        }),
        ('审核信息', {
            'fields': ('reviewer_notes', 'reviewer_approved'),
            'description': 'reviewer_approved: 勾选表示认证通过，不勾选表示未通过（无拒绝状态）'
        }),
    )
    
    readonly_fields = (
        'id_card_front_preview', 'id_card_back_preview','id_card_front', 'id_card_back', 'passport_image','health_certificate','chef_certificate',
        'health_cert_preview', 'chef_cert_preview', 
        'passport_preview', 'created_at', 'updated_at'
    )

    # 列表页缩略图显示（统一尺寸和样式）
    def id_card_front_thumbnail(self, obj):
        if obj.id_card_front:
            return format_html(
                '<a href="{}" target="_blank" title="点击查看原图">'
                '<img src="{}" style="width: 80px; height: auto; object-fit: cover; border: 1px solid #ddd; border-radius: 4px; padding: 2px;" />'
                '</a>',
                obj.id_card_front,
                obj.id_card_front
            )
        return "-"
    id_card_front_thumbnail.short_description = "身份证正面"

    def id_card_back_thumbnail(self, obj):
        if obj.id_card_back:
            return format_html(
                '<a href="{}" target="_blank" title="点击查看原图">'
                '<img src="{}" style="width: 80px; height: auto; object-fit: cover; border: 1px solid #ddd; border-radius: 4px; padding: 2px;" />'
                '</a>',
                obj.id_card_back,
                obj.id_card_back
            )
        return "-"
    id_card_back_thumbnail.short_description = "身份证反面"

    def passport_thumbnail(self, obj):
        if obj.passport_image:
            return format_html(
                '<a href="{}" target="_blank" title="点击查看原图">'
                '<img src="{}" style="width: 80px; height: auto; object-fit: cover; border: 1px solid #ddd; border-radius: 4px; padding: 2px;" />'
                '</a>',
                obj.passport_image,
                obj.passport_image
            )
        return "-"
    passport_thumbnail.short_description = "护照"

    def health_cert_thumbnail(self, obj):
        if obj.health_certificate:
            return format_html(
                '<a href="{}" target="_blank" title="点击查看原图">'
                '<img src="{}" style="width: 80px; height: auto; object-fit: cover; border: 1px solid #ddd; border-radius: 4px; padding: 2px;" />'
                '</a>',
                obj.health_certificate,
                obj.health_certificate
            )
        return "-"
    health_cert_thumbnail.short_description = "健康证明"

    def chef_cert_thumbnail(self, obj):
        if obj.chef_certificate:
            return format_html(
                '<a href="{}" target="_blank" title="点击查看原图">'
                '<img src="{}" style="width: 80px; height: auto; object-fit: cover; border: 1px solid #ddd; border-radius: 4px; padding: 2px;" />'
                '</a>',
                obj.chef_certificate,
                obj.chef_certificate
            )
        return "-"
    chef_cert_thumbnail.short_description = "厨师资格证"

    # 详情页大图预览（带预览区和原图按钮）
    def id_card_front_preview(self, obj):
        if obj.id_card_front:
            return format_html(
                '<div style="margin: 10px 0; max-width: 800px;">'
                '<p style="margin-bottom: 5px; font-weight: bold;">身份证正面预览：</p>'
                '<img src="{}" style="max-width: 100%; max-height: 500px; border: 1px solid #ddd; border-radius: 4px; margin-bottom: 8px;" />'
                '<div>'
                '<a href="{}" target="_blank" class="button" style="margin-right: 10px;">查看原图</a>'
                '<a href="{}" target="_blank" class="button" style="background-color: #4CAF50; color: white;">新窗口打开</a>'
                '</div>'
                '</div>',
                obj.id_card_front,
                obj.id_card_front,
                obj.id_card_front
            )
        return "-"
    id_card_front_preview.short_description = "身份证正面预览"

    def id_card_back_preview(self, obj):
        if obj.id_card_back:
            return format_html(
                '<div style="margin: 10px 0; max-width: 800px;">'
                '<p style="margin-bottom: 5px; font-weight: bold;">身份证反面预览：</p>'
                '<img src="{}" style="max-width: 100%; max-height: 500px; border: 1px solid #ddd; border-radius: 4px; margin-bottom: 8px;" />'
                '<div>'
                '<a href="{}" target="_blank" class="button" style="margin-right: 10px;">查看原图</a>'
                '<a href="{}" target="_blank" class="button" style="background-color: #4CAF50; color: white;">新窗口打开</a>'
                '</div>'
                '</div>',
                obj.id_card_back,
                obj.id_card_back,
                obj.id_card_back
            )
        return "-"
    id_card_back_preview.short_description = "身份证反面预览"

    def passport_preview(self, obj):
        if obj.passport_image:
            return format_html(
                '<div style="margin: 10px 0; max-width: 800px;">'
                '<p style="margin-bottom: 5px; font-weight: bold;">护照预览：</p>'
                '<img src="{}" style="max-width: 100%; max-height: 500px; border: 1px solid #ddd; border-radius: 4px; margin-bottom: 8px;" />'
                '<div>'
                '<a href="{}" target="_blank" class="button" style="margin-right: 10px;">查看原图</a>'
                '<a href="{}" target="_blank" class="button" style="background-color: #4CAF50; color: white;">新窗口打开</a>'
                '</div>'
                '</div>',
                obj.passport_image,
                obj.passport_image,
                obj.passport_image
            )
        return "-"
    passport_preview.short_description = "护照预览"

    def health_cert_preview(self, obj):
        if obj.health_certificate:
            return format_html(
                '<div style="margin: 10px 0; max-width: 800px;">'
                '<p style="margin-bottom: 5px; font-weight: bold;">健康证明预览：</p>'
                '<img src="{}" style="max-width: 100%; max-height: 500px; border: 1px solid #ddd; border-radius: 4px; margin-bottom: 8px;" />'
                '<div>'
                '<a href="{}" target="_blank" class="button" style="margin-right: 10px;">查看原图</a>'
                '<a href="{}" target="_blank" class="button" style="background-color: #4CAF50; color: white;">新窗口打开</a>'
                '</div>'
                '</div>',
                obj.health_certificate,
                obj.health_certificate,
                obj.health_certificate
            )
        return "-"
    health_cert_preview.short_description = "健康证明预览"

    def chef_cert_preview(self, obj):
        if obj.chef_certificate:
            return format_html(
                '<div style="margin: 10px 0; max-width: 800px;">'
                '<p style="margin-bottom: 5px; font-weight: bold;">厨师资格证预览：</p>'
                '<img src="{}" style="max-width: 100%; max-height: 500px; border: 1px solid #ddd; border-radius: 4px; margin-bottom: 8px;" />'
                '<div>'
                '<a href="{}" target="_blank" class="button" style="margin-right: 10px;">查看原图</a>'
                '<a href="{}" target="_blank" class="button" style="background-color: #4CAF50; color: white;">新窗口打开</a>'
                '</div>'
                '</div>',
                obj.chef_certificate,
                obj.chef_certificate,
                obj.chef_certificate
            )
        return "-"
    chef_cert_preview.short_description = "厨师资格证预览"

    # 操作按钮优化
    def action_buttons(self, obj):
        return format_html(
            '<a class="button" href="{}">编辑审核</a>',
            f"{obj.id}/change/"
        )
    action_buttons.short_description = "操作"
    action_buttons.allow_tags = True  # 允许HTML渲染

    # 优化审核状态同步逻辑
    def save_model(self, request, obj, form, change):
        # 记录状态变更前的值
        old_approved = None
        if change:
            old_obj = DjChefVerification.objects.get(pk=obj.pk)
            old_approved = old_obj.reviewer_approved

        super().save_model(request, obj, form, change)

        # 仅在审核状态实际变更时同步
        if change and old_approved is not None and obj.reviewer_approved != old_approved:
            obj.chef.verification_status = 'verified' if obj.reviewer_approved else 'unverified'
            obj.chef.save()


@admin.register(VerificationRecord)
class VerificationRecordAdmin(admin.ModelAdmin):
    list_display = ('chef', 'admin', 'created_at', 'verification_status', 'action_buttons')
    list_filter = ('created_at', 'id_front_verified', 'health_cert_verified')  # 细化筛选
    search_fields = ('chef__nickname', 'admin__username')
    readonly_fields = ('created_at',)  # 保护创建时间不被修改
    
    def verification_status(self, obj):
        # 优化显示逻辑：明确区分全部通过/部分通过
        all_verified = all([
            obj.id_front_verified, 
            obj.id_back_verified, 
            obj.health_cert_verified, 
            obj.chef_cert_verified
        ])
        return format_html(
            '<span style="color: {};">{}</span>',
            'green' if all_verified else 'orange',
            '全部通过' if all_verified else '部分通过'
        )
    verification_status.short_description = '验证状态'
    verification_status.allow_tags = True

    def action_buttons(self, obj):
        return format_html(
            '<a class="button" href="{}">查看详情</a>',  # 更明确的按钮文本
            f"{obj.id}/change/"
        )
    action_buttons.short_description = "操作"
    action_buttons.allow_tags = True